// pages/register/register.js
Page({
  data: {
    username: '',
    phone: '',
    verifyCode: '',
    countdown: 0,
    agreed: false,
    isFormValid: false,
    isUsernameFocused: false,
    isPhoneFocused: false,
    isVerifyCodeFocused: false,
    isPhoneValid: false
  },

  onLoad: function (options) {
    console.log('注册页面加载');
  },

  // 用户名输入
  onUsernameInput: function (e) {
    const username = e.detail.value;
    this.setData({ username });
    this.checkFormValid();
  },

  // 手机号输入
  onPhoneInput: function (e) {
    const phone = e.detail.value;
    const isPhoneValid = this.validatePhone(phone);
    
    this.setData({ 
      phone: phone,
      isPhoneValid: isPhoneValid
    });
    this.checkFormValid();
  },

  // 验证码输入
  onVerifyCodeInput: function (e) {
    const verifyCode = e.detail.value;
    this.setData({ verifyCode });
    this.checkFormValid();
  },

  // 输入框聚焦/失焦
  onUsernameFocus: function () { this.setData({ isUsernameFocused: true }); },
  onUsernameBlur: function () { this.setData({ isUsernameFocused: false }); },
  onPhoneFocus: function () { this.setData({ isPhoneFocused: true }); },
  onPhoneBlur: function () { this.setData({ isPhoneFocused: false }); },
  onVerifyCodeFocus: function () { this.setData({ isVerifyCodeFocused: true }); },
  onVerifyCodeBlur: function () { this.setData({ isVerifyCodeFocused: false }); },

  // 检查表单有效性
  checkFormValid: function () {
    const { username, phone, verifyCode, agreed, isPhoneValid } = this.data;
    const isValid = username.trim().length >= 2 && 
                   isPhoneValid && 
                   verifyCode.length === 6 && 
                   agreed;
    this.setData({ isFormValid: isValid });
  },

  // 获取验证码
  getVerifyCode: function () {
    const { phone, isPhoneValid } = this.data;

    if (!isPhoneValid) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return;
    }

    // 开始倒计时
    this.startCountdown();

    // 模拟发送验证码
    wx.showToast({ title: '验证码已发送', icon: 'success' });

    // 实际开发中这里调用后端API发送验证码
    console.log('发送验证码到:', phone);
  },

  // 开始倒计时
  startCountdown: function () {
    this.setData({ countdown: 60 });
    
    const timer = setInterval(() => {
      if (this.data.countdown <= 0) {
        clearInterval(timer);
        return;
      }
      this.setData({ countdown: this.data.countdown - 1 });
    }, 1000);
  },

  // 验证手机号格式
  validatePhone: function (phone) {
    return /^1[3-9]\d{9}$/.test(phone);
  },

  // 处理注册
  handleRegister: function () {
    const { username, phone, verifyCode } = this.data;

    // 表单验证
    if (username.trim().length < 2) {
      wx.showToast({ title: '用户名至少2个字符', icon: 'none' });
      return;
    }

    if (!this.validatePhone(phone)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return;
    }

    if (verifyCode.length !== 6) {
      wx.showToast({ title: '请输入6位验证码', icon: 'none' });
      return;
    }

    // 模拟验证码验证（测试验证码：123456）
    if (verifyCode !== '123456') {
      wx.showToast({ title: '验证码错误', icon: 'none' });
      return;
    }

    // 保存用户信息
    const userInfo = {
      nickname: username.trim(),
      phone: phone,
      avatar: '',
      desc: '欢迎使用记忆盒子'
    };

    wx.setStorageSync('userInfo', userInfo);
    wx.setStorageSync('isLoggedIn', true);

    // 注册成功
    wx.showToast({
      title: '注册成功',
      icon: 'success',
      success: () => {
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      }
    });
  },

  // 跳转到登录
  goToLogin: function () {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // 返回
  goBack: function () {
    wx.navigateBack();
  },

  // 协议相关
  toggleAgreement: function () {
    this.setData({ agreed: !this.data.agreed });
    this.checkFormValid();
  },

  showAgreement: function () {
    wx.showModal({
      title: '用户协议',
      content: '欢迎注册记忆盒子！请仔细阅读用户协议和隐私政策。',
      showCancel: false,
      confirmText: '我知道了'
    });
  }
});